package com.jing21.learn.authorizationservice.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;
import java.util.Map;

/**
 * Created by lenovo07 on 2016/12/28.
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
	@Autowired
	private CustomUserDetailService userService;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String username = authentication.getName();
		String password = (String) authentication.getCredentials();
		int login_type = 0;

		Object dobj = authentication.getDetails();
		if (dobj instanceof Map) {
			Map<String, Object> details = (Map<String, Object>) dobj;

			if (details.get("login_type") != null) {
				try {
					login_type = Integer.valueOf(details.get("login_type").toString());
				} catch (Exception e) {
					throw new BadCredentialsException("login_type is not int.");
				}

			}
		}

		UserDetails user = userService.loadUserByUsername(username);
		if (user == null) {
			throw new BadCredentialsException("用户不存在！");
		}

		if (login_type == 1) {
			boolean isvalidate = restTemplate.getForObject(
					"http://message-client/sms/v_sms_code?phone=" + username + "&code=" + password, Boolean.class);
			if (!isvalidate) {
				throw new BadCredentialsException("验证码不正确！");
			}
		} else {

			if(!passwordEncoder.matches(password,user.getPassword())){
				throw new BadCredentialsException("密码错误！");
			}
		}
		Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
		return new UsernamePasswordAuthenticationToken(user, password, authorities);
	}



	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}

}
